package com.alvis.exam.excle.vm;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;

import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;

public abstract class AbstratExcelUtil<T> {
	
	private Logger logger = LoggerFactory.getLogger(getClass());
	
	public List<T> parse(MultipartFile file) throws Exception{
		return parse(file.getInputStream());
	}
	
	public List<T> parse(File file) throws Exception{
		return parse(new FileInputStream(file));
	}
	
	public List<T> parse(String fileName) throws Exception{
		return parse(new FileInputStream(fileName));
	}
	
	public List<T> parse(InputStream inputStream){
		Workbook workbook = null;
		try {
			workbook = WorkbookFactory.create(inputStream);
			List<T> list = parseInteral(workbook);
			return list;
		} catch (Exception e) {
			e.printStackTrace();
			throw new RuntimeException(e.getMessage());
		}finally{
			if(inputStream!=null){
				try {
					inputStream.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			if(workbook!=null){
				try {
					workbook.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
	}

	public abstract List<T> parseInteral(Workbook workbook);

}
